package cn.weibo.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.weibo.env.constants.ApplicationConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import cn.weibo.entity.UserEntity;
import cn.weibo.service.UserService;

@Controller
@RequestMapping("/users")
public class UsersController {
	
	private final Logger log = LoggerFactory.getLogger(UsersController.class);
	
	@Resource(name = "userService")
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(UserEntity userEntity, HttpServletRequest request) {
        userService.insertUser(userEntity);
        log.debug("register method execution");
        request.getSession().setAttribute(ApplicationConstants.APPLICATION_USER_ATTRIBUTE, userEntity);
        return "redirect:/users/" + userEntity.getAccount();
    }

    @RequestMapping(value = "/checkAccount", produces = MediaType.APPLICATION_JSON_VALUE)
    public String check(@RequestParam("account") String account, ModelMap modelMap) {
        UserEntity userEntity = userService.getUserByAccount(account);
        if(userEntity != null) {
            modelMap.addAttribute("checkAccountFlag", false);
        } else {
            modelMap.addAttribute("checkAccountFlag", true);
        }
        return "jsonDefaultView";
    }

	@RequestMapping("/login")
	public void login(UserEntity userEntity) {
		log.debug("user = {}, password = {}", userEntity.getAccount(), userEntity.getPassword());
		throw new RuntimeException("exception");
	}
	
	@RequestMapping("/{userID}")
	public String getUserToJSON(@PathVariable long userID, ModelMap modelMap) {
		log.debug("userID = {}",userID);
		UserEntity user = new UserEntity();
		user.setUserID(userID);
		user.setCreatedOn(new Date());
		modelMap.addAttribute("user", user);
		return "jsonDefaultView";
	}
	
	@RequestMapping("/test/{userID}")
	public ModelAndView getUserToJSON(@PathVariable long userID) {
		UserEntity user = new UserEntity();
		user.setUserID(userID);
		user.setUserName("abc");
		user.setCreatedOn(new Date());
		ModelAndView mav = new ModelAndView();
		mav.addObject("user", user);
		mav.setViewName("jsonDefaultView");
		return mav;
	}


}
